package service

import (
	"fmt"
	"go-admin/internal/model"
	mr "go-admin/internal/model/api/model_request"
	ms "go-admin/internal/model/api/model_response"
)

func (s *Service) CreateMenu(param *mr.CreateMenuRequest) (string, error) {
	// 判断菜单是否存在
	//menu, err := s.dao.GetDeptByMenuTitle(param)
	//if err != nil {
	//	return menu.Id, err
	//}
	//// 判断是否存在
	//if menu.Id != "" {
	//	return menu.Id, errors.New("菜单已存在已存在")
	//}
	insertId, err := s.dao.CreateMenu(param)
	if err != nil {
		return insertId, err
	}
	return insertId, nil
}

// 获取菜单tree
func (s *Service) GetMenuTree() ([]*ms.ListMenuResponse, error) {
	// 获取所有的部门
	menuListAll, err := s.GetMenuListAll()
	if err != nil {
		return nil, err
	}
	resTree := ms.ModelToListMenuTreeRes(menuListAll)
	fmt.Println(resTree)
	// 将parentId为 '0' 的装进去
	list := make([]*ms.ListMenuResponse, 0)
	for _, r := range resTree {
		if r.ParentId != "0" {
			continue
		}
		list = append(list, coverMenuTree(resTree, r))
	}
	return list, nil
}

// 根据角色key获取获取菜单tree
func (s *Service) GetMenuTreeByRoleKey(roleKey []string) ([]*ms.ListMenuResponse, error) {
	// 获取所有的部门
	menuListAll, err := s.GetMenuListAll()
	if err != nil {
		return nil, err
	}
	resTree := ms.ModelToListMenuTreeRes(menuListAll)
	fmt.Println(resTree)
	// 将parentId为 '0' 的装进去
	list := make([]*ms.ListMenuResponse, 0)
	for _, r := range resTree {
		if r.ParentId != "0" {
			continue
		}
		list = append(list, coverMenuTree(resTree, r))
	}
	return list, nil
}

func coverMenuTree(list []*ms.ListMenuResponse, l *ms.ListMenuResponse) *ms.ListMenuResponse {
	// 存放找到的节点
	min := make([]*ms.ListMenuResponse, 0)
	for _, ls := range list {
		if l.Id != ls.ParentId {
			continue
		}
		mi := ms.ListMenuResponse{}
		mi.Id = ls.Id
		mi.ParentId = ls.ParentId
		mi.CreatedOn = ls.CreatedOn
		mi.IsBanned = ls.IsBanned
		mi.MenuTitle = ls.MenuTitle
		mi.Icon = ls.Icon
		mi.Path = ls.Path
		mi.Permission = ls.Permission
		mi.IsVisible = ls.IsVisible
		mi.MenuType = ls.MenuType
		mi.ComponentPath = ls.ComponentPath
		mi.RouteName = ls.RouteName
		mi.Children = []*ms.ListMenuResponse{}
		ms := coverMenuTree(list, &mi)
		min = append(min, ms)
	}
	l.Children = min
	return l
}

func (s *Service) GetMenuListAll() ([]*model.Menu, error) {
	return s.dao.GetMenuListAll()
}

// 根据角色key获取对应的菜单
func (s *Service) GetMenuListByRoleKey(roleKey []string) ([]*model.Menu, error) {
	return s.dao.GetMenuListByRoleKey(roleKey)
}

func (s *Service) GetMenuById(id string) (*model.Menu, error) {
	dept, err := s.dao.GetMenuById(id)
	if err != nil {
		return nil, err
	}
	// 判断是否存在
	if dept.Id == "" {
		return nil, err
	}
	return dept, nil
}

func (s *Service) UpdateMenu(param *mr.UpdateMenuRequest) error {
	return s.dao.UpdateMenu(param)
}

func (s *Service) DeleteMenu(id string) error {
	return s.dao.DeleteMenu(id)
}
